package com.base.cn.platform.os.common.mybatis;

import org.apache.ibatis.jdbc.SQL;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.Map;

/**
 * 删除数据SQL提供类
 */
public class BaseDeleteProvider extends BaseProvider{

    /**
     * 通过ID删除数据SQL生成方法
     * @param map
     * @return
     */
    public String deleteByIdTableName(Map<String,Object> map){
        Class clazz = (Class) map.get("clazz");
        BigDecimal id = (BigDecimal) map.get("id");
        String tableName = (String) map.get("tableName");
        String sql = getSQL(clazz,null,id,tableName);
        return sql;
    }

    /**
     * 通过ID删除数据SQL生成方法
     * @param map
     * @return
     */
    public String deleteById(Map<String,Object> map){
        Class clazz = (Class) map.get("clazz");
        BigDecimal id = (BigDecimal) map.get("id");
        String sql = getSQL(clazz,null,id);
        return sql;
    }

    /**
     * 条件删除
     * @param map
     * @return
     */
    public String deleteWhereSqlTableName(Map<String,Object> map){
        Class clazz = (Class) map.get("clazz");
        String whereSql = (String)map.get("whereSql");
        String tableName = (String)map.get("tableName");
        String sql = getSQL(clazz,whereSql,null,tableName);
        return sql;
    }

    /**
     * 条件删除
     * @param map
     * @return
     */
    public String deleteWhereSql(Map<String,Object> map){
        Class clazz = (Class) map.get("clazz");
        String whereSql = (String)map.get("whereSql");
        String sql = getSQL(clazz,whereSql,null);
        return sql;
    }

    private String getSQL(Class clazz,String whereSql,BigDecimal id){
        String tableName = clazz.getSimpleName();
        return this.getSQL(clazz,whereSql,id,tableName);
    }

    private String getSQL(Class clazz,String whereSql,BigDecimal id,String tableName){
        SQL sql = new SQL();
        sql.DELETE_FROM(tableName);
        if(!StringUtils.isEmpty(whereSql)){
            sql.WHERE(whereSql);
        }
        if(id!=null){
            sql.WHERE("id="+id);
        }
        return sql.toString();
    }
}
